//
//  EMAudioRecordHelper.m
//  ChatDemo-UI3.0
//
//  Created by XieYajie on 2019/2/14.
//  Copyright © 2019 XieYajie. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>

#import "XGAudioRecordHelper.h"
#import "amrFileCodec.h"

@interface XGAudioRecordHelper()<AVAudioRecorderDelegate>

/// 开始时间
@property (nonatomic, strong) NSDate *startDate;
/// 结束时间
@property (nonatomic, strong) NSDate *endDate;
/// 录音对象
@property (nonatomic, strong) AVAudioRecorder *recorder;
/// 录音配置
@property (nonatomic, strong) NSDictionary *recordSetting;
/// 录音完成回调
@property (nonatomic, copy) void (^recordFinished)(NSString *aPath, NSInteger aTimeLength);

@end

@implementation XGAudioRecordHelper

#pragma mark - 单例

+ (instancetype)sharedHelper
{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[XGAudioRecordHelper alloc] init];
    });
    
    return instance;
}

- (void)dealloc
{
    [self stopRecord];
}

#pragma mark - AVAudioRecorderDelegate

// 录音完成回调
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder
                           successfully:(BOOL)flag
{
    // 录音时长
    NSInteger timeLength = [[NSDate date] timeIntervalSinceDate:_startDate];
    NSString *recordPath = [_recorder.url path];
    
    if (flag) {
        // 将wav格式转换为amr
//        NSString *amrFilePath = [[recordPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"amr"];
//        BOOL success = [self convertWAV:recordPath toAMR:amrFilePath];
        // 删除源wav文件
//        [[NSFileManager defaultManager] removeItemAtPath:recordPath error:nil];
//        recordPath = success ? amrFilePath : nil;
//        timeLength = success ? timeLength : 0;
    } else {
        // 录音失败
        recordPath = nil;
        timeLength = 0;
    }
    
    if (_recordFinished) {
        _recordFinished(recordPath,timeLength);
    }
    
    [self stopRecord];
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
    // 录音出错
    if (_recordFinished) {
        _recordFinished(nil,0);
    }
    
    [self stopRecord];
}

#pragma mark - 公开方法

// 开始录音
- (void)startRecordWithPath:(NSString *)aPath
                 completion:(void(^)(NSError *error))aCompletion
{
    NSError *error = nil;
    do {
        // 正在录音
        if (self.recorder && self.recorder.isRecording) {
            error = [NSError errorWithDomain:@"正在进行录制" code:-1 userInfo:nil];
            break;
        }
        
        // 真机需要添加以下录音代码
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&error];
        if (!error){
            [[AVAudioSession sharedInstance] setActive:YES error:&error];
        }
        if (error) {
            error = [NSError errorWithDomain:@"AVAudioSession SetCategory失败" code:-1 userInfo:nil];
            break;
        }
        
        // 保存路径
        NSString *wavPath = [[aPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"wav"];
        NSURL *wavUrl = [[NSURL alloc] initFileURLWithPath:wavPath];
        self.recorder = [[AVAudioRecorder alloc] initWithURL:wavUrl settings:self.recordSetting error:nil];
        BOOL success = [self.recorder prepareToRecord];
        if (success) {
            self.startDate = [NSDate date];
            self.recorder.meteringEnabled = YES;
            self.recorder.delegate = self;
            success = [self.recorder record];
        }
        
        if (!success) {
            [self stopRecord];
            error = [NSError errorWithDomain:@"准备录制工作失败" code:-1 userInfo:nil];
        }
        
    } while (0);
    
    if (aCompletion) {
        aCompletion(error);
    }
}

// 停止录音
-(void)stopRecordWithCompletion:(void(^)(NSString *aPath, NSInteger aTimeLength))aCompletion
{
    self.recordFinished = aCompletion;
    [self.recorder stop];
}

// 取消录音
- (void)cancelRecord
{
    [self stopRecord];
}

#pragma mark - 私有方法

///// 格式转换
///// @param aWavPath Wav格式
///// @param aAmrPath amr格式
//- (BOOL)convertWAV:(NSString *)aWavPath toAMR:(NSString *)aAmrPath
//{
//    BOOL success = NO;
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    if ([fileManager fileExistsAtPath:aAmrPath]) {
//        success = YES;
//    } else if ([fileManager fileExistsAtPath:aWavPath]) {
//        EM_EncodeWAVEFileToAMRFile([aWavPath cStringUsingEncoding:NSASCIIStringEncoding], [aAmrPath cStringUsingEncoding:NSASCIIStringEncoding], 1, 16);
//        if ([fileManager fileExistsAtPath:aAmrPath]) {
//            success = YES;
//        }
//    }
//
//    return success;
//}

/// 停止录音
- (void)stopRecord
{
    if (_recorder) {
        _recorder.delegate = nil;
        if (_recorder.recording) {
            [_recorder stop];
        }
    }
    
    _recorder = nil;
    _recordFinished = nil;
    _startDate = nil;
    _endDate = nil;
}

#pragma mark - 懒加载

- (NSDictionary *)recordSetting
{
    if (!_recordSetting) {
        _recordSetting = @{
        AVSampleRateKey: @(8000.0),
        AVFormatIDKey: @(kAudioFormatLinearPCM),
        AVLinearPCMBitDepthKey: @(16),
        AVNumberOfChannelsKey: @(1),
        AVEncoderAudioQualityKey: @(AVAudioQualityHigh)
        };
    }

    return _recordSetting;
}

@end
